/*
 *  CSE 40166, Computer Graphics, Fall 2013
 *
 *  PORT
 *  File: enemy.cpp
 *
 *  Kevin Sonnen
 *
 *  Description: Class representing the enemies in the game. Derived from vehicle class
 *
 */
 
#include "enemy.h"
#include "drawShapes.h"

//
// enemy()
//
// Constructor for the enemy class, initializes position and some other variables
//
enemy::enemy() {
	// Initialize position to (0, 0)
	enemyState = DEAD;
	position.push_back(0);
	position.push_back(0);
	velocity.push_back(0);
	velocity.push_back(0);
	vehicleSpeed = 4;
	//rotationAngle = 0.0f;
	//rotationSpeed = 0.1f;
	radius = 15.0f;
	explosionRadius = 1.0f;
	explosionColor.push_back(1.0);
	explosionColor.push_back(0.0);
	explosionColor.push_back(0.0);
	explosionColor.push_back(1.0);
}

enemy::~enemy() {
}

//
// draw()
//
// Draw the enemy. If it's alive, draw a circle. If it's exploding, draw an expanding explosion
//
void enemy::draw() {
	//static float explosionRadius = 1.0f;
	//static GLfloat explosionColor[4] = {1.0f, 0.0f, 0.0f, 1.0f};
	if (enemyState==ALIVE) {
		glPushMatrix();
		glColor3f( 1.0f, 0.0f, 0.0f );
		glTranslatef( position[0], position[1], 0 );
		drawCircle(radius, false);
		glPopMatrix();
	} else if (enemyState==EXPLODING) {
		// Draw expanding explosion
		glPushMatrix();
		glTranslatef( position[0], position[1], 0 );
		// RED -> GREEN (FADING ALPHA)
		const int numLines = 15;
		float explosionAngle = 0.0f;
		for (int i=0; i<numLines; ++i) {
			glRotatef( explosionAngle, 0, 0, 1 );
			//glColor4fv( explosionColor );
			glColor4f( explosionColor[0], explosionColor[1], explosionColor[2], explosionColor[3] );
			glBegin( GL_LINES ); {
				glVertex2f(-explosionRadius, 0);
				glVertex2f(explosionRadius, 0);
			}; glEnd();
			explosionAngle += 2;
		}
		// Update size and color of explosion
		explosionRadius += 1.2f;
		if (explosionColor[0] > 0)
			explosionColor[0] -= .02f;
		if (explosionColor[1] < 1)
			explosionColor[1] += .02f;
		if (explosionColor[3] > 0)
			explosionColor[3] -= .015f;
		glPopMatrix();
	}
}

//
// void updatePosition(const ship &myShip)
//
// Move the enemy towards the player, with some randomness thrown in
//
void enemy::updatePosition(const ship &myShip) {
	// Calculate the distance of the enemy from the player ship
	std::vector<float> shipPos = myShip.position;
	float distanceX = shipPos[0] - position[0];
	float distanceY = shipPos[1] - position[1];
	float distanceFromPlayer = sqrtf(powf(distanceX, 2) + powf(distanceY, 2));
	
	const int crashRadius = 25;
	
	if (distanceFromPlayer > crashRadius) {
		// Set velocity to chase player
		velocity[0] = vehicleSpeed * (distanceX/distanceFromPlayer) * (2*(float) rand()/RAND_MAX);
		velocity[1] = vehicleSpeed * (distanceY/distanceFromPlayer) * (2*(float) rand()/RAND_MAX);
	
		// Update position
		position[0] += velocity[0];
		position[1] += velocity[1];
	}
}
